<script>
  import BaseDialog from '@/components/BaseDialog/index.vue'
  import Component from 'vue-class-component'
  import { ref } from '@vue/composition-api'
  import { baseURL } from '@/config/default/setting.config'
  import { fileToBase64 } from '@/utils/index'
  import adApi from '@/api/AdApi'
  import productApi from '@/api/ProductApi'
  import { Prop } from 'vue-property-decorator'
  @Component({
    name: 'AdvertisementDialog',
    setup() {
      const file = ref(null)
      const form = ref(null)
      return {
        file,
        form,
        baseURL,
      }
    },
  })
  export default class Advertisement extends BaseDialog {
    get title() {
      return (this.model.id ? '编辑' : '新增') + '广告'
    }

    @Prop({
      required: true,
      type: Array,
    })
    bindProducts

    model = {
      id: null,
      file: null,
      assetId: null,
      assetName: '',
      description: '',
    }

    previewUrl = ''

    products = []

    setModel(model) {
      if (model) {
        Object.assign(this.model, model)
        this.previewUrl = this.baseURL + model.serverPath
      }
      return this
    }

    async getProducts() {
      let resp = await productApi.getAll()
      if (resp && resp.data) {
        this.products = resp.data.map((x) => {
          return {
            label: x.productName,
            value: x.id,
            id: x.id,
          }
        })
      } else {
        this.$message.error('获取产品列表失败!')
      }
    }

    get productsOptions() {
      return this.products.map((x) => {
        return {
          ...x,
          disabled: this.bindProducts.includes(x.id),
        }
      })
    }

    get props() {
      return {
        assetId: {
          label: '广告图片',
          tag: 'el-select',
          style: {
            width: '100%',
          },
          initValue: null,
        },
        assetName: {
          visible: false,
          initValue: null,
        },
        id: {
          visible: false,
          initValue: null,
        },
        productId: {
          label: '关联产品',
          tag: 'el-select',
          options: this.productsOptions,
          initValue: null,
          filterable: true,
          initValue: null,
          style: {
            width: '100%',
          },
        },
        description: {
          label: '广告介绍',
          type: 'textarea',
          initValue: null,
          rows: 5,
          placeholder: '请输入广告介绍',
        },
      }
    }

    async onSubmit() {
      let formData = new FormData()
      formData.append('state', 1)
      Object.entries(this.model).forEach(([prop, value]) => {
        formData.append(prop, value)
      })
      let resp = await (!this.model.id
        ? adApi.create(formData)
        : adApi.update(formData))
      if (resp && resp.code == 0) {
        this.$message.success('保存成功!')
        this.$emit('update')
        this.onClose()
      } else {
        this.$message.error('保存失败!')
      }
    }

    onClose() {
      this.form && this.form.clearForm()
      this.file && (this.file.value = '')
      this.previewUrl = null
      this.closeLoading()
      this.closeDialog()
    }

    config = {
      labelSuffix: '：',
    }

    handleSelect() {
      this.file && this.file.click()
    }

    async handleChange(ev) {
      var fileEle = ev.target
      var file = fileEle.files && fileEle.files[0]
      if (!file) {
        return
      }
      this.previewUrl = await fileToBase64(file)
      //清理之前的文件，防止下次重复不会触发change
      this.file.value = ''
      this.model.file = file
      this.model.assetName = file.name
    }

    get theme() {
      return this.previewUrl ? 'success' : 'primary'
    }

    get tooltip() {
      return this.previewUrl ? '重新选择' : '选择图片'
    }

    renderBody(h) {
      return (
        <base-form
          v-model={this.model}
          ref="form"
          {...{
            props: {
              props: this.props,
              config: this.config,
            },
            scopedSlots: {
              assetId: ({ model }) => {
                return (
                  <div class="file-prop">
                    <div class="file-row">
                      <input
                        class="file-region"
                        on-change={this.handleChange}
                        type="file"
                        ref="file"
                      />
                      <el-input
                        placeholder="请选择图片"
                        readonly
                        class="file-input"
                        v-model={model.assetName}
                      ></el-input>
                      <el-button
                        class="file-btn"
                        type={this.theme}
                        on-click={this.handleSelect}
                      >
                        {this.tooltip}
                      </el-button>
                    </div>
                    <div class="file-row">
                      {this.previewUrl ? (
                        <img class="preview-img" src={this.previewUrl} />
                      ) : (
                        <span>暂无预览</span>
                      )}
                    </div>
                  </div>
                )
              },
            },
          }}
        ></base-form>
      )
    }

    mounted() {
      this.getProducts()
    }
  }
</script>

<style lang="scss" scoped>
  .file-row {
    display: flex;
    &:not(:last-child) {
      margin-bottom: 20px;
    }
    .file-region {
      display: none !important;
    }
    .file-input {
      flex: 1;
      margin-right: 20px;
    }
    .file-btn {
      width: 100px;
    }
  }

  .preview-img {
    max-width: 100%;
    max-height: 200px;
  }
</style>
